/*
 * CursosAdmin.java
 *
 * Created on 24 de diciembre de 2007, 3:26
 */
package jschoolmanagerportable.gui;

import java.awt.Component;
import javax.swing.JOptionPane;
import jschoolmanagerportable.gui.util.Dialogo;
import jschoolmanagerportable.model.Colegio;
import jschoolmanagerportable.model.Curso;

/**
 *
 * @author  Administrador
 */
public class CursosAdminView extends javax.swing.JInternalFrame {

    /** Creates new form CursosAdmin */
    public CursosAdminView() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = javax.persistence.Persistence.createEntityManagerFactory("JSchoolManagerPortablePU").createEntityManager();
        colegioQuery = entityManager.createQuery("SELECT c FROM Colegio c");
        colegioList = org.jdesktop.observablecollections.ObservableCollections.observableList(colegioQuery.getResultList());
        cursoQuery = entityManager.createQuery("SELECT c FROM Curso c");
        cursoList = org.jdesktop.observablecollections.ObservableCollections.observableList(cursoQuery.getResultList());
        colegiosCombo = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaCursos = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        cursoIdText = new javax.swing.JTextField();
        cursoNombreText = new javax.swing.JTextField();
        cursoDescripcionText = new javax.swing.JTextField();
        botonGuardar = new javax.swing.JButton();
        botonBorrar = new javax.swing.JButton();
        botonNuevo = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(jschoolmanagerportable.JSchoolManagerPortableApp.class).getContext().getResourceMap(CursosAdminView.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N

        colegiosCombo.setName("colegiosCombo"); // NOI18N

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, colegioList, colegiosCombo);
        bindingGroup.addBinding(jComboBoxBinding);

        colegiosCombo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                colegiosComboActionPerformed(evt);
            }
        });

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tablaCursos.setName("tablaCursos"); // NOI18N

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, cursoList, tablaCursos);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${id}"));
        columnBinding.setColumnName("Id");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${nombre}"));
        columnBinding.setColumnName("Nombre");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${descripcion}"));
        columnBinding.setColumnName("Descripcion");
        columnBinding.setColumnClass(String.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(tablaCursos);

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        cursoIdText.setEditable(false);
        cursoIdText.setName("cursoIdText"); // NOI18N

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, tablaCursos, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.id}"), cursoIdText, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        cursoNombreText.setName("cursoNombreText"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, tablaCursos, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.nombre}"), cursoNombreText, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        cursoDescripcionText.setName("cursoDescripcionText"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, tablaCursos, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.descripcion}"), cursoDescripcionText, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        botonGuardar.setText(resourceMap.getString("botonGuardar.text")); // NOI18N
        botonGuardar.setName("botonGuardar"); // NOI18N
        botonGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonGuardarActionPerformed(evt);
            }
        });

        botonBorrar.setText(resourceMap.getString("botonBorrar.text")); // NOI18N
        botonBorrar.setName("botonBorrar"); // NOI18N
        botonBorrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonBorrarActionPerformed(evt);
            }
        });

        botonNuevo.setText(resourceMap.getString("botonNuevo.text")); // NOI18N
        botonNuevo.setName("botonNuevo"); // NOI18N
        botonNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonNuevoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 385, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(colegiosCombo, 0, 319, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cursoIdText, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(cursoNombreText, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cursoDescripcionText, javax.swing.GroupLayout.PREFERRED_SIZE, 290, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(10, 10, 10))
            .addGroup(layout.createSequentialGroup()
                .addGap(84, 84, 84)
                .addComponent(botonGuardar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(botonBorrar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(botonNuevo)
                .addContainerGap(119, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {botonBorrar, botonGuardar, botonNuevo});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(colegiosCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cursoIdText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(cursoNombreText, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(cursoDescripcionText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(botonGuardar)
                    .addComponent(botonBorrar)
                    .addComponent(botonNuevo))
                .addContainerGap(13, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void colegiosComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_colegiosComboActionPerformed

        Colegio colegio = (Colegio) colegiosCombo.getSelectedItem();
        cursoQuery = entityManager.createQuery("SELECT c FROM Curso c WHERE c.idcolegio = :id");
        if (colegio == null) {
            return;
        }
        cursoQuery.setParameter("id", colegio);
        cursoList.clear();
        cursoList.addAll(cursoQuery.getResultList());
        tablaCursos.repaint();
    }//GEN-LAST:event_colegiosComboActionPerformed

    private void botonGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonGuardarActionPerformed
        if (cursoIdText.getText().length() == 0) {
            JOptionPane.showMessageDialog(this, "Debe seleccionar un registro de la tabla");
            return;
        }
        Curso curso = new Curso();
        curso.setId(Integer.parseInt(cursoIdText.getText()));
        curso.setNombre(cursoNombreText.getText());
        curso.setDescripcion(cursoDescripcionText.getText());
        Colegio colegio = (Colegio) colegiosCombo.getSelectedItem();
        curso.setIdcolegio(colegio);
        entityManager.getTransaction().begin();
        entityManager.merge(curso);
        entityManager.getTransaction().commit();
        cursoIdText.setText(String.valueOf(curso.getId())); 
    }//GEN-LAST:event_botonGuardarActionPerformed

    private void botonBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonBorrarActionPerformed

        Curso curso = new Curso();
        curso.setId(Integer.parseInt(cursoIdText.getText()));
        curso.setNombre(cursoNombreText.getText());
        curso.setDescripcion(cursoDescripcionText.getText());
        Colegio colegio = (Colegio) colegiosCombo.getSelectedItem();
        curso.setIdcolegio(colegio);
        try {
            entityManager.getTransaction().begin();
            curso = entityManager.merge(curso);
            entityManager.remove(curso);
            entityManager.getTransaction().commit();
            cursoList.remove(curso);
            int row = cursoList.size() - 1;
            if (row != -1) {
                tablaCursos.setRowSelectionInterval(row, row);
                tablaCursos.scrollRectToVisible(tablaCursos.getCellRect(row, 0, true));
            }else{
                limpiaCampos();
            }
            tablaCursos.repaint();
        } catch (Exception e) {
            Dialogo.alert("Error", "No se pudo borrar el Curso", (Component) evt.getSource());
        }
    }//GEN-LAST:event_botonBorrarActionPerformed

    private void botonNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonNuevoActionPerformed

        Curso curso = new Curso();
        curso.setNombre("nombre");
        curso.setDescripcion("descripcion");
        Colegio colegio = (Colegio) colegiosCombo.getSelectedItem();
        curso.setIdcolegio(colegio);
        entityManager.getTransaction().begin();
        entityManager.persist(curso);
        entityManager.getTransaction().commit();
        cursoList.add(curso);
        int row = cursoList.size() - 1;
        tablaCursos.setRowSelectionInterval(row, row);
        tablaCursos.scrollRectToVisible(tablaCursos.getCellRect(row, 0, true));
        tablaCursos.repaint();
        cursoNombreText.requestFocus();        
    }//GEN-LAST:event_botonNuevoActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonBorrar;
    private javax.swing.JButton botonGuardar;
    private javax.swing.JButton botonNuevo;
    private java.util.List<jschoolmanagerportable.model.Colegio> colegioList;
    private javax.persistence.Query colegioQuery;
    private javax.swing.JComboBox colegiosCombo;
    private javax.swing.JTextField cursoDescripcionText;
    private javax.swing.JTextField cursoIdText;
    private java.util.List<jschoolmanagerportable.model.Curso> cursoList;
    private javax.swing.JTextField cursoNombreText;
    private javax.persistence.Query cursoQuery;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tablaCursos;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    public void limpiaCampos(){
        this.cursoIdText.setText("");
        this.cursoDescripcionText.setText("");
        this.cursoNombreText.setText("");
    }
}
